package luxing.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;

public class ValidatorUtil {

	private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	public static <T> String validate(T obj) {
		Map<String, String> errorMap = new HashMap<String, String>();
		StringBuffer msg = new StringBuffer();
		Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
		if (set != null && set.size() > 0) {
			String property = null;
			for (ConstraintViolation<T> cv : set) {
				// 这里循环获取错误信息，可以自定义格式
				property = cv.getPropertyPath().toString();
				if (errorMap.get(property) != null) {
					errorMap.put(property, errorMap.get(property) + "," + cv.getMessage());
				} else {
					errorMap.put(property, cv.getMessage());
				}
			}
		}
		for (String errorMsg : errorMap.values()) {
			msg = msg.append(errorMsg).append("<br/>");
		}
		return msg.toString();
	}

}